package com.xiyuan.controller.user;

import com.xiyuan.constant.MessageConstant;
import com.xiyuan.constant.UserConstant;
import com.xiyuan.pojo.result.PageBean;
import com.xiyuan.pojo.result.Result;
import com.xiyuan.pojo.entity.User;

import com.xiyuan.service.UserService;
import com.xiyuan.utils.JwtUtil;
import com.xiyuan.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
//    @Autowired
//    private JwtProperties jwtProperties;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 用户注册
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/register")
    public Result register(
            @Pattern(regexp = "^\\S{5,16}$") String username,
            @Pattern(regexp = "^\\S{5,16}$") String password,
            @Pattern(regexp = "^\\S{2,16}$")String name){
        //查询用户
        User u = userService.findByUserName(username);
        if (u == null){
            //表明没有被占用
            //注册
            User user = new User();
            user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
            user.setUsername(username);
            user.setName(name);
            user.setRole(UserConstant.ROLE_USER);
            userService.register(user);
            return Result.success();
        }else {
            //占用
            return Result.error("用户名已被占用");
        }

    }


    /**
     * 用户登录
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username,
                                @Pattern(regexp = "^\\S{5,16}$") String password) {
        log.info("用户登录：{}", username);
        //根据用户名查询用户
        User loginUser = userService.findByUserName(username);
        //判断该用户是否存在
        if (loginUser == null) {
            return Result.error(MessageConstant.USER_NOT_FOUND);
        }
        if (loginUser.getStatus() == UserConstant.USER_STATUS_DISABLE) {
            return Result.error(MessageConstant.ACCOUNT_LOCKED);
        }
        //判断密码是否正确 loginUser中password是密文
        // String password1 = Md5Util.getMD5String(password); //自定义工具类
        if (DigestUtils.md5DigestAsHex(password.getBytes()).equals(loginUser.getPassword())) {
            //登录成功
            //生成秘钥
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", loginUser.getId());
            claims.put("username", loginUser.getUsername());
            String token = JwtUtil.createJWT(
                    "abcdefghijklmnopqrstuvwxyz",
                    2,
                    claims
            );
            //把token存储到redis中用于后续的校验
            ValueOperations<String, String> operations = redisTemplate.opsForValue();
            operations.set(token, token, 2, TimeUnit.HOURS);

            return Result.success(token);
        } else {
            return Result.error(MessageConstant.USER_PASSWORD_ERROR);
        }

    }

    /**
     * 获取用户信息
     * @return
     */
    @GetMapping("/userInfo")
    public Result<User> getInfo(){
        Map map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        return Result.success(userService.findUserById(id));
    }

    @PutMapping("/updateUser")
    public Result updateUser(@RequestBody User user){
        userService.updateUser(user);
        return Result.success();
    }

    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @Validated(User.UpdateAvatar.class) String avatarUrl){
        User user = new User();
        Map map = ThreadLocalUtil.get();
        user.setId((Integer) map.get("id"));
        user.setAvatarUrl(avatarUrl);
        userService.updateUser(user);
        return Result.success();
    }

    /**
     * 修改密码
     * @param params
     * @param token
     * @return
     */
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String,String> params,@RequestHeader("Authorization") String token){
        //校验参数
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");

        if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)){
            return Result.error("参数未填写完整");
        }
        if(newPwd.length() < 5 || newPwd.length() > 16){
            return  Result.error("新密码参数错误");
        }

        //调用userService根据用户名拿到原密码和oldPwd作比较
        Map map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User loginUser = userService.findByUserName(username);
        if (!DigestUtils.md5DigestAsHex(oldPwd.getBytes()).equals(loginUser.getPassword())){
            return Result.error("原密码错误");
        }

        if (!newPwd.equals(rePwd)){
            return Result.error("两次密码不一致");
        }
        //校验成功，调用userService更新用户密码
        loginUser.setPassword(DigestUtils.md5DigestAsHex(newPwd.getBytes()));
        userService.updateUser(loginUser);
        //同时删除redis中对应的token
//        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
//        operations.getOperations().delete(token);
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        operations.getOperations().delete(token);
        return Result.success();

    }

    /**
     * 获取用户列表
     * @return
     */
    @GetMapping("/userList")
    public Result<PageBean<User>> list(User user){
        return Result.success(userService.getList(user));
    }

    /**
     * 添加管理员
     * @param user
     * @return
     */
    @PostMapping("/admin")
    public Result addAdmin(@RequestBody User user){
        User byUserName = userService.findByUserName(user.getUsername());
        if (byUserName == null){
            userService.addAdmin(user);
        }else {
            return Result.error("用户名已存在");
        }
        return Result.success();
    }
}
